<!--
 * @Description:试情管理
-->
<template>
  <BaseMainSlot>
    <template v-slot:zhactbar>
      <ActionBar
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-save="false"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:content>
      <el-table
        ref="tableDataTryRef"
        :data="tableData"
        style="width: 100%"
        max-height="88%"
        border
        highlight-current-row
        @current-change="handleCurrentChange"
        @selection-change="handleSelect"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column label="试情母羊">
          <template slot-scope="scope">
            <div>
              <span v-for="(item,index) in scope.row.tryLoveFemaleNameList" :key="index">
                <span v-if="item" class="title">{{ (item)?(item.name):"-" }}</span>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="怀孕母羊">
          <template slot-scope="scope">
            <div>
              <span v-for="(item,index) in scope.row.pregnantFemaleNameList" :key="index">
                <span v-if="item" class="title">{{ (item)?(item.name):"-" }}</span>
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="facilityName" label="合养羊舍">
          <template>
            <span>{{ facility }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合养持续时间">
          <template slot-scope="scope">
            <span>{{ ((scope.row.tryLoveDate))?(`${(formatDateTime(scope.row.tryLoveDate))}`) :"没有记录!!!" }}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加 -->
      <el-dialog title="添加试情记录" :visible.sync="addTryLoveDialog">
        <el-form ref="addTeaserRef" :model="addTeaser" label-position="left" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="试情日期:"
                prop="tryLoveDate"
                :rules="[{
                  reqsuired: true, message: '请选择试情日期', trigger: ['blur','change']
                }]"
              >
                <el-date-picker
                  v-model="addTeaser.tryLoveDate"
                  placeholder="选择日期时间"
                  type="date"
                  value-format="yyyy-MM-dd"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="选择怀孕母羊:">
            <el-checkbox-group v-model="addTeaser.pregnantFemaleList">
              <el-checkbox
                v-for="(item,index) in tryLoveList"
                :key="index+'add'"
                :label="item.result.bionId "
                border
                @change="changePre($event,item.result.bionId)"
              >{{ item.result.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addTryLoveDialog = false">取 消</el-button>
          <el-button type="primary" @click="ensure">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 修改 -->
      <el-dialog title="修改试情记录" :visible.sync="updateDialog">
        <el-form
          ref="updateTeaserRef"
          :model="updateTeaser"
          label-position="left"
          label-width="100px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="试情日期:"
                prop="tryLoveDate"
                placeholder="选择日期时间"
                :rules="[{
                  reqsuired: true, message: '请选择开始时间', trigger: ['blur','change']
                }]"
              >
                <el-date-picker
                  v-model="updateTeaser.tryLoveDate"
                  placeholder="选择日期时间"
                  clearable
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="选择怀孕母羊:">
            <el-checkbox-group v-model="updateTeaser.pregnantFemaleList">
              <el-checkbox
                v-for="(item,index) in updateTeaser.showLoveList"
                :key="index+'updata'"
                :label="item.bionId"
                border
                @change="changePre($event)"
              >{{ item.name }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addTryLoveDialog = false">取 消</el-button>
          <el-button type="primary" @click="updateEnsure">确 定</el-button>
        </div>
      </el-dialog>
      <Pagination
        :page-size="pageSizeTry"
        :current-page="currentPageTry"
        :total-size="tryLength"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
  </BaseMainSlot>
</template>

<script>
import Pagination from "@/components/Pagination";
import ActionBar from "@/components/ActionBar/index";
import BaseMainSlot from "@/components/BaseMainSlot/baseone.vue";
import reqs from "@/api/digital-production/breeding-management/teaser-management/index";
import { mymixin } from "@/utils/mixin";
export default {
  name: "TeaserManagement",
  components: {
    Pagination,
    ActionBar,
    BaseMainSlot
  },
  mixins: [mymixin],
  data() {
    return {
      tryLength: 0,
      queryID: "",
      tableData: [],
      form: {},
      addTryLoveDialog: false,
      tryLoveDate: "",
      pregnantFemaleList: [],
      tryLoveFemaleList: [],
      // 原始数据
      originalData: [],
      // 试情母羊列表
      tryLoveList: [],
      showLoveList: [],
      // 怀孕母羊列表
      pregnantEwe: [],
      showPregnantEwe: [],
      facility: "",
      updateDialog: false,
      tryLoveId: "",
      delID: [],
      addTeaser: {
        tryLoveDate: "",
        pregnantFemaleList: []
      },
      updateTeaser: {
        tryLoveDate: "",
        raiseRecordId: "",
        showLoveList: [],
        pregnantFemaleList: []
      }
    };
  },
  watch: {
    nowChanceStau(newval) {
      if (newval === "add") {
        this.addTryLoveDialog = true;
      } else if (newval === "edit") {
        this.updateDialog = true;
        // eslint-disable-next-line no-empty
      } else if (newval === "cancel") {
      }
    },
    addTryLoveDialog(newval) {
      if (!newval) {
        this.addTeaser = {
          tryLoveDate: "",
          pregnantFemaleList: [""],
          tryLoveFemaleList: [""]
        };
        this.$refs.addTeaserRef.resetFields();
      }
    },
    updateDialog(newval) {
      if (!newval) {
        this.nowChanceStau = "";
        this.$refs.updateTeaserRef.resetFields();
      }
    }
  },
  created() {
    if (this.$route.params) {
      this.queryID = this.$route.params.raiseRecordId;
      this.facility = this.$route.params.facility;
      this.pagingQuery();
    }
    this.getDate();
  },
  methods: {
    //
    changePre(val, id) {},
    // 添加
    ensure() {
      this.$refs["addTeaserRef"].validate(valid => {
        if (valid) {
          let tryId = [];
          this.tryLoveList.forEach(item => {
            tryId.push(item.result.bionId);
          });
          let params = {
            organizationNo: sessionStorage.getItem("organizationNo"),
            pregnantFemaleList: this.addTeaser.pregnantFemaleList,
            raiseRecordId: this.queryID,
            tryLoveDate: this.addTeaser.tryLoveDate,
            tryLoveFemaleList: tryId
          };
          reqs.postAdd(params).then(res => {
            if (res.code === 1) {
              this.$message.success("添加成功");
              this.addTeaser = {
                tryLoveDate: "",
                pregnantFemaleList: [""],
                tryLoveFemaleList: [""]
              };
              this.addTryLoveDialog = false;
              this.pagingQuery();
            } else {
              this.$message.error(`${res.msg}!!!`);
            }
          });
        } else {
          this.$message.error("请将信息填写完整！！！");
          return false;
        }
      });
    },
    // 分页查询
    pagingQuery() {
      reqs
        .postQueryPageByCondition(this.queryID, {
          page: this.currentPageTry,
          size: this.pageSizeTry
        })
        .then(res => {
          if (res.code === 1) {
            let result = res.data || {};
            this.tryLength = result.totalElements;
            result = result.content || [];
            this.tableData = result;
          }
        });
    },
    // 获取初始化数据 试情母羊的列表
    async getDate() {
      await reqs.getQueryBionByMatrix(this.queryID).then(res => {
        if (res.code === 1) {
          let result = [];
          res.data.forEach(item => {
            result.push({
              result: item,
              isShow: false
            });
          });
          this.tryLoveList = result;
          this.originalData = JSON.parse(JSON.stringify(result));
          this.originalData.forEach(item => {
            item.isShow = true;
          });
          this.showPregnantEwe = JSON.parse(JSON.stringify(this.originalData));
        }
      });
    },

    // 选中当前行
    handleCurrentChange(val) {
      if (val) {
        this.editActive = true;
        this.cancelActive = true;
        let preId = [];
        let tryId = [];
        this.updateTeaser.showLoveList = val.tryLoveFemaleNameList;
        val.pregnantFemaleNameList.forEach(item => {
          preId.push(item.bionId);
        });
        val.tryLoveFemaleNameList.forEach(item => {
          tryId.push(item.bionId);
        });
        this.updateTeaser.tryLoveDate = val.tryLoveDate;
        this.updateTeaser.pregnantFemaleList = preId;
        this.updateTeaser.raiseRecordId = val.raiseRecordId;
        this.updateTeaser.tryLoveId = val.tryLoveId;
        this.updateTeaser.tryLoveFemaleList = preId;
      }
    },
    cancel() {
      this.$refs.tableDataTryRef.setCurrentRow();
      this.$refs.tableDataTryRef.clearSelection();
      this.nowChanceStau = "";
      this.addActive = true;
      this.cancelActive = false;
      this.editActive = false;
    },
    // 修改试情记录
    updateEnsure() {
      this.$refs["updateTeaserRef"].validate(valid => {
        if (valid) {
          let tryId = "";
          tryId = this.updateTeaser.tryLoveId;
          let params = {
            organizationNo: sessionStorage.getItem("organizationNo"),
            pregnantFemaleList: this.updateTeaser.pregnantFemaleList,
            raiseRecordId: this.updateTeaser.raiseRecordId,
            tryLoveDate: this.updateTeaser.tryLoveDate,
            tryLoveFemaleList: this.updateTeaser.tryLoveFemaleList,
            tryLoveId: tryId
          };
          reqs.postEdit(params).then(res => {
            if (res.code === 1) {
              this.$message.success("修改成功！！！");
            } else {
              this.$message.error("修改失败！！！");
            }
          });
          this.getDate();
          this.updateDialog = false;
        } else {
          this.$message.error("请将信息填写完整！！！");
          return false;
        }
      });
    },
    // 删除
    delmessage() {
      reqs
        .postDelByIdList(this.delID)
        .then(res => {
          if (res.code === 1) {
            this.$message.success("删除成功！！！");
            this.pagingQuery();
          } else {
            this.$message.error("删除失败！！！");
          }
        })
        .catch(res => {});
      this.pagingQuery();
    },
    //
    handleSelect() {
      let result = this.$refs.tableDataTryRef.selection;
      result.forEach(item => {
        this.delID.push(item.tryLoveId);
      });
      if (result.length > 0) {
        this.delActive = true;
        this.cancelActive = true;
      } else {
        this.delActive = false;
        this.cancelActive = false;
      }
    },
    // 分页功能实现
    changePageSize(pageSizeTry) {
      this.pageSizeTry = pageSizeTry;
      this.pagingQuery();
    },
    changeCurrentPage(currentPageTry) {
      this.currentPageTry = currentPageTry;
      this.pagingQuery();
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-table {
  overflow: auto;
}
::v-deep .el-input__inner {
  background-color: transparent;
}
::v-deep .el-form-item__label {
  color: #fff;
}
::v-deep .el-dialog__header {
  background-color: #006e91;
}
::v-deep .el-dialog__body {
  background: #0085a0;
  color: #fff;
  .el-input {
    width: 100%;
  }
  .el-select {
    //充满父元素（el-col）
    width: 100%;
  }
}
.title {
  cursor: pointer;
  margin-left: 5px;
}
</style>
